new Vue({
    el: '#app',
    data() {
        return {
            isflageIOX: true,
            currentOrg: '',
            agentList: [],
            checkAgentUser: [],
            multiChoose: false,
            chooseAll: false,

            chooseUserPop: false,
            toChooseUser: [],
            checkUser: [],
            chooseUserAll: false,
            refreshing: false,
            loading: false,
            finished: false,
            searchUser: '',
            pageNum: 0,
            pageSize: 20,
        }
    },
    watch: {

    },
    created() {
        const _this = this
        let jsApiList = []
        $.getScript("../../../js/jweixin-sgccigw-1.0.0.js" /*"js/jweixin-1.0.0.js"*/, function () {
            'use strict';
            wx.ready(function () {
                wx.onHistoryBack(() => {
                    _this.home()
                    return false
                })
            });
            jsApiList = [
                'onHistoryBack',
            ];
            wx.config({
                beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: corpid,
                timestamp: '1626832073',
                nonceStr: nonceStr,
                signature: signature,
                jsApiList: jsApiList
            });
        });
    },
    mounted() {
        this.compatibleInput()

        this.queryAgentUserList()
    },
    methods: {
        handleMultiChooseShow() {
            this.multiChoose = false
            this.chooseAll = false
            this.checkAgentUser = []
        },
        toggle(index, checkItem) {
            const exist = this.checkAgentUser.some(item => item.id === checkItem.id)
            if(!exist) {
                //选中,且全部选中
                if(this.checkAgentUser.length + 1 == this.agentList.length) {
                    this.chooseAll = true
                }
            }else {
                this.chooseAll = false
            }
            this.$refs.checkboxes[index].toggle()
        },
        toggleUser(index, checkItem) {
            const exist = this.checkUser.some(item => item.id === checkItem.id)
            if(!exist) {
                //选中,且全部选中
                if(this.checkUser.length + 1 == this.toChooseUser.length) {
                    this.chooseUserAll = true
                }
            }else {
                this.chooseUserAll = false
            }
            this.$refs.checkboxes2[index].toggle()
        },
        chooseAgentAllClick(event) {
            if(this.chooseAll) {
                this.$refs.checkboxes.forEach(item => {
                    item.toggle(true);
                })
            }else {
                this.$refs.checkboxes.forEach(item => {
                    item.toggle(false);
                })
            }
        },
        chooseUserAllClick(event) {
            if(this.chooseUserAll) {
                this.$refs.checkboxes2.forEach(item => {
                    item.toggle(true);
                })
            }else {
                this.$refs.checkboxes2.forEach(item => {
                    item.toggle(false);
                })
            }
        },
        onAdd() {
            this.chooseUserPop = true
            this.loading = false
            this.finished = false
            this.pageNum = 0
            this.toChooseUser = []
            // this.queryChooseAgentUser()
        },
        handleDeleteAgentUser() {
            if(null == this.checkAgentUser || 0 == this.checkAgentUser.length) {
                mui.toast('请先选择代理人', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }

            mui.confirm("是否删除代理人", "删除代理人", ["取消", "确定"], (e) => {
                if (e.index == 1) {
                    let ids = this.checkAgentUser.map(item => item.id).join(',')
                    this.deleteAgentUser(ids)
                } else {
                }
            });
        },
        handleAddUser() {
            if(null == this.checkUser || 0 == this.checkUser.length) {
                mui.toast('请先选择用户', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }
            let agentUserIds = this.checkUser.map(item => item.userId).join(',')
            this.addAgentUser(agentUserIds)
        },
        closeChooseUserPop() {
            this.searchUser = ''
            this.chooseUserPop = false
            this.chooseUserAll = false
            this.checkUser = []
        },
        queryAgentUserList() {
            $(".curtain").css("display", "block");
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/agentUser/queryAgentUserList",
                type: "post",
                // async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                           this.agentList = res.resultValue
                           this.agentList.forEach(user => {
                                let orgNamePaths = user.agentOrgNamePath.split("/").reverse()
                                if(orgNamePaths.length > 2) {
                                    this.$set(user, 'showOrgName', orgNamePaths[1] + "/" + orgNamePaths[0])
                                }else {
                                    this.$set(user, 'showOrgName', user.agentOrgNamePath)
                                }
                           })
                           if(null != this.agentList && 0 < this.agentList.length) {
                               this.currentOrg = this.agentList[0]['agentOrgName']
                           }
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                    $(".curtain").css("display", "none");
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        deleteAgentUser(ids) {
            $(".curtain").css("display", "block");
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "ids": ids,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/agentUser/deleteAgentUser",
                type: "post",
                // async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            this.multiChoose = false
                            this.queryAgentUserList()
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                    $(".curtain").css("display", "none");
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        onRefresh() {
            // 清空列表数据
            this.finished = false;

            // 重新加载数据
            // 将 loading 设置为 true，表示处于加载状态
            this.loading = true;
            this.pageQueryChooseAgentUser();
        },
        searchChooseAgentUser() {
            this.toChooseUser = []
            this.queryChooseAgentUser()
        },
        pageQueryChooseAgentUser() {
            if (!this.finished) {
                this.pageNum += 1
                setTimeout(() => {
                    // 这里替换为你的实际数据刷新逻辑
                    this.refreshing = false;
                    this.queryChooseAgentUser(this.pageNum)
                }, 1000);
            }
        },
        //查询可选择的代理用户
        queryChooseAgentUser(page) {
            // $(".curtain").css("display", "block");
            if (this.refreshing) {
                this.refreshing = false;
            }
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "pageNumber": page? page : 1,
                "pageSize": this.pageSize,
                "searchUser": this.searchUser,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/agentUser/queryChooseAgentUser",
                type: "post",
                // async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                           let tmpUsers = res.resultValue
                           tmpUsers.forEach(user => {
                                let orgNamePaths = user.baseOrgNamePath.split("/").reverse()
                                if(orgNamePaths.length > 2) {
                                    this.$set(user, 'showOrgName', orgNamePaths[1] + "/" + orgNamePaths[0])
                                }else {
                                    this.$set(user, 'showOrgName', user.baseOrgNamePath)
                                }
                                this.toChooseUser.push(user)
                           })
                           
                           if(0 == tmpUsers.length) {
                            this.finished = true
                           }
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                    $(".curtain").css("display", "none");
                    this.loading = false
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    this.loading = false
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        addAgentUser(agentUserIds) {
            $(".curtain").css("display", "block");
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "agentUserIds": agentUserIds,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/agentUser/addAgentUser",
                type: "post",
                // async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            this.closeChooseUserPop()
                            this.queryAgentUserList()
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                    $(".curtain").css("display", "none");
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        // 判断安卓还是ios
        compatibleInput() {
            //获取浏览器的userAgent,并转化为小写
            var ua = navigator.userAgent.toLowerCase();
            //判断是否是苹果手机，是则是true
            var isIos = ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1;
            if (isIos) {
                this.isflageIOX = true;
            } else {
                this.isflageIOX = false;
            }
        },
        home() {
            $(location).attr("href", "../../Home.html");
        },
        createSgin(data) {
            let hashData = sm3(data);
            let hashData_last = sm3(hashData);
            hashData_last = hashData_last.substr(0, 5);
            hashData += hashData_last;
            let sign = hashData;
            return sign;
        },
    }
})